package com.xin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xin.constants.EmployeeConstants;
import com.xin.entity.crm.DeptEntity;
import com.xin.entity.crm.EmployEntity;
import com.xin.entity.crm.dto.LoginDto;
import com.xin.exception.MyException;
import com.xin.mapper.EmployeeMapper;
import com.xin.service.DeptService;
import com.xin.service.EmployeeService;
import com.xin.utils.ExcelUtils;
import com.xin.utils.FileUtils;
import com.xin.utils.JWTUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

/**
 * 员工
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, EmployEntity> implements EmployeeService {

    /**
     * 注入redisTemplate
     */
    @Resource
    private RedisTemplate redisTemplate;
    /**
     * 注入部门业务类
     */
    @Resource
    private DeptService deptService;
    /**
     * 分页查询所有员工数据
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<EmployEntity> findAll(Integer page, Integer size) {
        Page<EmployEntity> pages = new Page<>(page,size);
        //连笔查询所有员工数据
        List<EmployEntity> list = this.baseMapper.findAll(page-1, size, null);
        pages.setTotal(this.baseMapper.selectCount(null));
        pages.setRecords(list);
        return pages;
    }

    /**
     * 根据员工名称模糊查询员工数据
     * @param name
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<EmployEntity> findByNameLike(String name,Integer page,Integer size) {
        List<EmployEntity> list = this.baseMapper.findAll(page-1, size, name);
        Page<EmployEntity> pages = new Page<>(page,size);
        QueryWrapper<EmployEntity> employEntityQueryWrapper = new QueryWrapper<>();
        employEntityQueryWrapper.like("username",name);
        //封装当前数据
        pages.setRecords(list);
        //设置总的查询条数
        pages.setTotal(this.baseMapper.selectCount(employEntityQueryWrapper));
        return pages;
    }

    /**
     * 添加员工数据
     * @param employEntity
     * @return
     */
    @Override
    @Transactional
    public Integer add(EmployEntity employEntity) {
        this.checkEmployData(employEntity);
        boolean save = this.save(employEntity);
        return save?1:0;
    }
    /**
     * 修改员工部门数据
     * @param employEntity
     * @return
     */
    @Override
    @Transactional
    public Integer update(EmployEntity employEntity) {
        //校验员工数据
        this.checkEmployData(employEntity);
        int i = this.baseMapper.updateById(employEntity);
        return i;
    }

    /**
     * 批量删除员工数据
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Integer deleteBatch(List<Long> ids) {
        //校验被删除的员工里面是否含有主管信息
        List<DeptEntity> managerList = this.deptService.getBaseMapper().selectList(new QueryWrapper<DeptEntity>().in("manager_id", ids));
        if (managerList!=null&&managerList.size()>=1) throw new MyException("被删除的员工中含有部门主管,无法删除");
        /**
         * 删除员工数据
         */
        int result = this.baseMapper.deleteBatchIds(ids);
        return result;
    }

    @Override
    public void checkEmployData(EmployEntity employEntity) {
        //校验员工部门信息是否存在
        DeptEntity deptEntity = this.deptService.getBaseMapper().selectOne(new QueryWrapper<DeptEntity>().eq("id", employEntity.getDepartmentId()));
        if (deptEntity==null) throw new MyException("部门信息不存在");

    }

    /**
     * 员工登录
     * @param employEntity
     * @return
     */
    @Override
    public LoginDto employeeLogin(EmployEntity employEntity) {
        EmployEntity employEntity1 = this.baseMapper.selectOne(new QueryWrapper<EmployEntity>().eq("username", employEntity.getUsername()).eq("password", employEntity.getPassword()));
        if (employEntity1==null) throw new MyException("用户名或密码错误");
        //查看账号状态
        if (employEntity1.getState()!=1) throw new MyException("当前账号状态不给予登录");

        if (employEntity1!=null) {
            //生成用户token
            String token = JWTUtils.getToken(employEntity);
            //存入员工登录信息到redis当中
            redisTemplate.boundValueOps(EmployeeConstants.LOGIN+token).set(employEntity1);
            LoginDto loginDto = new LoginDto(token,employEntity1.getId());

            return loginDto;
        }
        throw new MyException("用户名或密码错误");
    }

    /**
     * 根据员工id查找
     * @param employeeId
     * @return
     */
    @Override
    public EmployEntity findById(Long employeeId) {

        return this.baseMapper.selectById(employeeId);
    }

    /**
     * 导出全部excel数据
     * @param response
     */
    @Override
    public void exportAllData(HttpServletResponse response) {
        List<EmployEntity> employEntityList = this.baseMapper.findAllList();
        try {
            ExcelUtils.exportData(employEntityList,response,EmployEntity.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException("导出excel失败");
        }

    }

    /**
     * 导出指定数据
     * @param
     * @param response
     */
    @Override
    public void exportData( List<EmployEntity> list, HttpServletResponse response) {
        try {
            ExcelUtils.exportData(list,response,EmployEntity.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException("导出excel失败");
        }
    }

    /**
     * 导入数据
     * @param file
     * @return
     */
    @Override
    @Transactional
    public Integer importData(MultipartFile file,HttpServletResponse response) {
        //上传文件获得文件路径
        String filePath = FileUtils.fileUpload(file);
        //创建输入流
        try {
            FileInputStream inputStream = new FileInputStream(new File(filePath));
            //导入excel文件
            List<Object> objects = ExcelUtils.importData(inputStream, response, EmployEntity.class);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new MyException("导入失败");
        }
        return 1;
    }
}
